package com.zs4sdk;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.common.library.data.CommonEventHandler;
import com.common.library.data.EventHandler2Get;
import com.common.library.listener.OnProcessListener;
import com.common.library.util.ActivityHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.AutoLoginJSONResultEntity;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.extra.Zs4GameCode;
import com.zs4sdk.extra.Zs4GameInfo;
import com.zs4sdk.activity.login.Zs4GameLoginActivity;
import com.zs4sdk.common.Zs4GameUtil;
import com.zs4sdk.statistics.Zs4GameStatistics;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import org.apache.http.NameValuePair;

/**
 * Created by Administrator on 2018/4/23.
 */

public class Zs4Game extends Zs4GameBase {
     public Zs4Game() {
        super();
    }

    public void init(Zs4GameInfo info, OnProcessListener listener){
         super.init(info,listener);
        // Tracking.initWithKeyAndChannelId(info.getCtx().getApplicationContext(),RE_YUN_APP_KEY,"_default_");
        Zs4GameStatistics.initWithKeyAndChannelId(info.getCtx());
    }
    /**
     * function: 登录
     *
     * @param ctx
     * @param listener
     * @ author: aXiBa 2013-4-15 下午4:08:56
     */
    public void login(final Context ctx, final OnProcessListener listener) {
      //  super.login();
        doCheckLogin(ctx,listener);
    }
    private boolean isLogin(){
        boolean is = false;
        return is;
    }
    /**
     * 检测
     */
    private void doCheckLogin(final Context ctx, OnProcessListener listener) {

        // 注册登录广播接收
        final String action = getPackageName().concat(Extra.ACTIONKEY.LOGIN_POSTFIX);
        registerReceiver(action, listener);

        // 隐藏悬浮菜单
        Zs4GameMenu.hiddenStartMenu(ctx);

        // 1.7.0.1:判断是否已经登录(解决：很多游戏在登录页面就显示菜单，是自动分配的账号时会登录两次)
        if (isUseIdLogin(ctx)) {
            loginSuccess();
            ActivityHelper.sendBroadcast(action, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);
            Zs4GameMenu.closeActivitysAndShowStartMenu(ctx, action);
        } else {
            LoginJSONResultEntity entity = Zs4GameData.getInstance().getLastLoginedUserInfo();
            if(entity != null && entity.isSuccess()) {
                goLoginOrRegister(ctx,null);
            }else {
                ArrayList<LoginJSONResultEntity> list = Zs4GameData.getInstance().getUserInfoListOrderForUpdateTime();
                int len = list.size();
                if(len == 0){
                    Intent intent = new Intent();
                    intent.setClass(ctx,Zs4GameLoginActivity.class);
                    intent.putExtra("loginStyle",101);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ctx.startActivity(intent);
                }else{
                    checkVerifyForLastLoginAccount(ctx, action);
                }
            }
        }
    }

    private void loginSuccess(){
        LoginJSONResultEntity entity = Zs4GameData.getInstance().getLastLoginedUserInfo();
        Zs4GameData.getInstance().setLoginJSONResultEntity(entity);
    }
    /**
     * function: 验证最后登录账号
     *
     * @param ctx
     * @param action
     * @ author: aXiBa 2013-12-4 下午3:08:05
     */
    protected void checkVerifyForLastLoginAccount(final Context ctx, final String action) {
        if (NetworkHelper.isNetworkAvailable(ctx)) {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            String url =    Extra.URL.GUESTREGISTERURL;
            url =    Extra.URL.CHECKLOGIN;
            new EventHandler2Get(
                    url,//USER_REGIESTER_ACCOUUNT GUESTREGISTERURL
                    paramList,
                    ParamsHelper.getUserAgent1(),
                    new CommonEventHandler.ResultHandlerInEvent() {

                        @Override
                        public void doResultHanler(JSONObject result) throws JSONException {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                            AutoLoginJSONResultEntity entity = new AutoLoginJSONResultEntity(result);
                            Log.e("check"," checkLogin entity is "+entity.toString());

                            if(Helper.isNotNull(entity) && entity.isSuccess()){
                                Zs4GameMenu.synLocalAutoAssignInfo(entity);
                                Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity);
                                if(Zs4GameUtil.getUserIdIsLogin(ctx,entity.getUserId())){//已经登录过了
                                    boolean isSwitchAccount = Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity);
                                    ActivityHelper.sendBroadcast(action, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);
                                    Zs4GameMenu.closeActivitysAndShowStartMenu1(ctx, action);
                                    //Zs4GameMenu.startMenu(ctx);
                                }else{
                                    goLoginOrRegister(ctx,null);
                                }

                            }else{
                                Intent intent = new Intent();
                                intent.setClass(ctx,Zs4GameLoginActivity.class);
                                intent.putExtra("loginStyle",101);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                ctx.startActivity(intent);
                            }

                        }

                        @Override
                        public void doExceptionHandler() {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                        }
                    });
        } else {
        }
    }

    /**
     * function: 到登录或者注册页面
     *
     * @param ctx
     * @ author: aXiBa 2013-12-12 下午12:01:16
     */
    protected void goLoginOrRegister(Context ctx, String action) {

        Intent intent = new Intent();
        intent.setClass(ctx,Zs4GameLoginActivity.class);
        intent.putExtra("loginStyle",102);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(intent);
    }
    private boolean isUseIdLogin(Context context){
        LoginJSONResultEntity entity = Zs4GameData.getInstance().getLastLoginedUserInfo();
        if(entity == null){
            return false;
        }
        boolean is = Zs4GameUtil.getUserIdIsLogin(context,entity.getUserId());
        Log.e("login"," isUseIdLogin is "+is);
        return is;
    }
    public void onResume(Context context) {

        if(isUseIdLogin(context)) {
            Zs4GameMenu.startMenu(context);
        }else {
            hiddenLogoButton(context);
        }
        LogUtil.i("zs4gameGame-Activity-Life","onResume");
    }
    public void onRestart(Context context) {
        if(isUseIdLogin(context)) {
            Zs4GameMenu.startMenu(context);
        }else {
            hiddenLogoButton(context);
        }
        Zs4GameData.getInstance().setCanShowWelcomeToast(true);
        LogUtil.i("zs4gameGame-Activity-Life","onRestart");

    }

}
